module es {

    export class SpinePool {

        protected static _pool: Laya.SpineSkeleton[] = [];
        public static PushBack(spineInst: Laya.SpineSkeleton, sign?: string) {

            if (!spineInst) {
                es.Debug.error(`You try push nullptr to SpinePool. sign: ${sign}`)
                return
            }

            if (undefined == spineInst['POOL_KEY'] && !sign) {
                es.Debug.error("Pool Key undefined")
                es.Debug.debug && console.log(spineInst)
                return
            }

            let pool = SpinePool._pool
            let idx = pool.indexOf(spineInst);
            (idx == -1) && pool.push(spineInst)
            sign = sign || spineInst['POOL_KEY'];
            sign && SpinePool.Clean(spineInst)
            sign && SpinePool.Sign(sign, spineInst)
            sign && Laya.Pool.recover(sign, spineInst)
        }

        protected static Sign(poolSign: string, spineInst: Laya.SpineSkeleton) {
            spineInst['POOL_KEY'] = poolSign;
        }

        protected static Clean(spineInst: Laya.SpineSkeleton) {
            spineInst.parent && spineInst.removeSelf();
            spineInst.offAll(Laya.Event.STOPPED);
            spineInst.stop();
        }

        public static Malloc(sign: string) {
            if (!sign || sign.length < 1) {
                es.Debug.error("error sign: " + sign)
                return null
            }
            return Laya.Pool.getItem(sign)
        }
        public static Recycle(spineInst: Laya.SpineSkeleton) {
            if (!spineInst || !spineInst['POOL_KEY']) {
                es.Debug.error("Recycle: spineInst is null or not pool object")
                return;
            }
            SpinePool.Clean(spineInst)
            Laya.Pool.recover(spineInst['POOL_KEY'], spineInst);
        }

        public static TrackAllSpineRecycle2LayaPool() {
            let pool = SpinePool._pool;
            for (let i = 0; i < pool.length; i++) {
                if (!pool[i] || pool[i].destroyed) {
                    pool.splice(i--, 1);
                    continue;
                }
                SpinePool.Clean(pool[i])
                Laya.Pool.recover(pool[i]['POOL_KEY'], pool[i])
            }
        }
    }

}